const path = require('path')
const fs = require("fs")
const upperFirst = require("lodash/upperFirst");
const camelCase = require("lodash/camelCase");


exports.baseUrl = path.join(__dirname, "../src/");

exports.remove = (url) => {
	if (fs.existsSync(url)) {
		fs.unlinkSync(url)
	}
}

exports.viewNameFormat = (value) => {
	return upperFirst(camelCase(value))
}

exports.sleep = (sec = 1) => {
	return () => {
		return new Promise(resolve => {
			setTimeout(() => {
				resolve("sleeped!")
			}, sec * 1000)
		})
	}
}


/**
 * 
 * @param {String} filePath 文件路径
 * @description 获取组件中的configuration信息
 */
exports.getConfiguration = (filePath) => {
	if (!fs.existsSync(filePath)) {
		return false
	}
	const str = fs.readFileSync(filePath).toString();
	let [configurations] = str.match(/(?<=configurations\:) {([\s\S]*?)}/g) || ["{}"];
	// console.log(configurations);
	// eval("configurations =" + configurations);
	return configurations

}

/**
 * 
 * @param {string} name 路由/组件名称
 * @param {string} configuration 组件configuration
 * @param {string} rootPath 引入组件时的根目录
 * @description 获取路由
 */
exports.getRoute = (name, configuration, rootPath) => {
	if (!name || !configuration) return false;
	return {
		name,
		loadPath: `${rootPath}/${name}/index.vue`,
		meta: configuration
	}
}

/**
 * 
 * @description 根据layout目录下的文件获取布局
 */
exports.getLayouts = () => {
	const layouts = {};
	const layoutsDir = path.join(this.baseUrl, "layout");
	const rootPath = "@/layout"
	fs.readdirSync(layoutsDir).forEach((name) => {
		const layoutPath = path.join(layoutsDir, `${name}/index.vue`);
		const layout = this.getRoute(name, this.getConfiguration(layoutPath), rootPath);
		if (layout) {
			layouts[name] = layout;
		}
	});
	return layouts
}

/**
 *
 * @description 根据views目录下的文件获取页面
 */
exports.getViews = () => {
	const routes = {};
	const routesDir = path.join(this.baseUrl, "views");
	const rootPath = "@/views"
	fs.readdirSync(routesDir).forEach((layout) => {
		const routeOfLayout = path.join(routesDir, layout);
		do {
			let firstClassRoute = this.getRoute(layout, this.getConfiguration(path.join(routeOfLayout, "index.vue")), rootPath);
			if (!firstClassRoute) break;
			routes[layout] = firstClassRoute;
			return
		} while (false);
		fs.readdirSync(routeOfLayout).forEach((name) => {
			const routePath = path.join(routeOfLayout, `${name}/index.vue`);
			const route = {
				...this.getRoute(name, this.getConfiguration(routePath), `${rootPath}/${layout}`),
				layout
			};
			if (route) {
				routes[name] = route;
			}
		});

	});
	return routes
}

const { exec } = require("child_process");
/**
 * @name 以命令行的形式调用下一个plop
 * @returns 
 */
exports.nextPlop = (plopName = "") => [
	exec(`npm run new ${plopName}`)
]